//
//  MCIconManag.m
//  QuKeClient
//
//  Created by delicious on 2017/12/26.
//  Copyright © 2017年 delicious. All rights reserved.
//

#import "MCIconManager.h"


@interface UIViewController (showMessage)
+ (void)showAlertWithTitle: (NSString *)title message: (NSString *)message actionTitles: (NSArray<NSString *> *)actions cancelTitle: (NSString *)cancelTitle style: (UIAlertControllerStyle)style completion: (void(^)(NSInteger index))completion;
@end
@implementation UIViewController (showMessage)

+ (void)showAlertWithTitle: (NSString *)title message: (NSString *)message actionTitles: (NSArray<NSString *> *)actions cancelTitle: (NSString *)cancelTitle style: (UIAlertControllerStyle)style completion: (void(^)(NSInteger index))completion {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:style];
    for (NSInteger index = 0; index < actions.count; index++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:actions[index] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            !completion ?  : completion(index);
        }];
        [alert addAction:action];
    }
    if (cancelTitle.length) {
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
    }
    UIViewController *vc = [[UIApplication sharedApplication] keyWindow].rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
}


@end



@interface MCIconManager()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, copy) ReturnImage returnImage;
@property (nonatomic, copy) ReturnError returnError;
@end

@implementation MCIconManager

-(void)dealloc
{
    NSLog(@"图片选择管理释放了");
}

+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage
{
    return [MCIconManager onImageForVC:vc canEditImage:edit ReturnImage:returnImage ReturnError:nil Titles:@[@"相册",@"照相机"]];
}
+(instancetype)onImageForVC:(UIViewController *)vc ReturnImage:(ReturnImage)returnImage
{
       return [MCIconManager onImageForVC:vc canEditImage:NO ReturnImage:returnImage ReturnError:nil Titles:@[@"相册",@"照相机"]];
}

+(instancetype)onImageForVC:(UIViewController *)vc ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error
{
   return [MCIconManager onImageForVC:vc canEditImage:NO ReturnImage:returnImage ReturnError:error Titles:@[@"相册",@"照相机"]];
}
+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error
{
  
    return [MCIconManager onImageForVC:vc canEditImage:edit ReturnImage:returnImage ReturnError:error Titles:@[@"相册",@"照相机"]];
}


+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error Titles:(NSArray *)titles
{

    MCIconManager *iconManage = [MCIconManager new];
    iconManage.returnImage = returnImage;
    iconManage.returnError =error;
    
    [UIViewController showAlertWithTitle:@"选择图片方式" message:nil actionTitles:titles cancelTitle:@"取消" style:UIAlertControllerStyleActionSheet completion:^(NSInteger index) {
        
        if (index!=titles.count) {
            
            if (index==1) {
                UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                
                if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = iconManage;//weakSelf;
                    //设置拍照后的图片可被编辑
                    picker.allowsEditing = edit;
                    picker.sourceType = sourceType;
                    
                    [vc presentViewController:picker animated:YES completion:nil];
                    
                }else{
                    
                    error(@"该设备不支持拍照");
                    
                    [UIAlertController showAlertWithTitle:@"该设备不支持拍照" message:nil actionTitles:@[@"确定"] cancelTitle:nil style:UIAlertControllerStyleAlert completion:nil];
                    
                    return ;
                }
                
            }
            else if (index==0)
            {
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.delegate = iconManage;//weakSelf;
                //设置拍照后的图片可被编辑
                picker.allowsEditing = edit;
                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [vc presentViewController:picker animated:YES completion:nil];
                
            }
            
        }else
        {
            [iconManage removeFromSuperview];
        }
        
    }];
    [vc.view addSubview:iconManage];
    
    return iconManage;
}


#pragma mark - UIImagePickerController Delegate

///拍照、选视频图片、录像 后的回调（这种方式选择视频时，会自动压缩，但是很耗时间）
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
//{
//        UIImage * newImage = [info objectForKey:UIImagePickerControllerEditedImage];
//        //如果 picker 没有设置可编辑，那么image 为 nil
//        if (newImage == nil) {
//            newImage = [info objectForKey:UIImagePickerControllerOriginalImage];
//        }
//      //图片旋转
//    if (newImage.imageOrientation != UIImageOrientationUp) {
//        //图片旋转
//        newImage = [self fixOrientation:newImage];
//    }
//
//       __weak typeof(self)weakSelf=self;
//        dispatch_async(dispatch_get_main_queue(), ^{
//            weakSelf.returnImage(weakSelf,newImage);
//        });
//    [picker dismissViewControllerAnimated:YES completion:^{
//        [self removeFromSuperview];
//    }];
//}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)info
{
    
    //        UIImage * newImage = [info objectForKey:UIImagePickerControllerEditedImage];
    //        //如果 picker 没有设置可编辑，那么image 为 nil
    //        if (newImage == nil) {
    //            newImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    //        }
    __weak typeof(self)weakSelf=self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.returnImage(weakSelf,image);
    });
    [picker dismissViewControllerAnimated:YES completion:^{
        [weakSelf removeFromSuperview];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
           __weak typeof(self)weakSelf=self;
    [picker dismissViewControllerAnimated:YES completion:^{
        weakSelf.returnError(@"取消");
        [weakSelf removeFromSuperview];
    }];
    
    
}


#pragma mark 图片处理方法
//图片旋转处理
- (UIImage *)fixOrientation:(UIImage *)aImage {
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


@end



